﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Script.Serialization;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using ESN.Models;
using ESN.Languages;
using ESN.Helpers;
using System.IO;
using System.Configuration;

namespace ESN.Controllers
{
    [Authorize]
    public class GroupController : Controller
    {
        private ESNCoreDbContext core = new ESNCoreDbContext();
        [AllowAnonymous]
        public ActionResult Index()
        {
            return RedirectToAction("Index", "Home");
        }
        [AllowAnonymous]
        public ActionResult Home(int id)
        {
            var group = core.Groups.Include("Members").Where(g => g.GId == id).Single();
            if (group == null)
            {
                ViewBag.Detail = "Group not found";
                return View("Error");
            }
            ViewBag.Owner = PermissionHelper.IsOwner(id);
            if (ViewBag.Owner)
            {
                ViewBag.PostWall = true;
                ViewBag.ReadWall = true;
            }
            else
            {
                ViewBag.PostWall = PermissionHelper.postWall(id);
                ViewBag.ReadWall = PermissionHelper.readWall(id);
            }
            if (ViewBag.ReadWall)
            {
                ViewBag.First20Walls = core.GroupWalls.Include("Writer").Include("Children").Include("Attachments").Where(w => w.GId == id && w.ParentGWId == null).OrderByDescending(w => w.GWId).Take(20);
            }
            if (!PermissionHelper.isMember(id) && !PermissionHelper.IsOwner(id))
            {
                ViewBag.ShowFriendRequest = true;
            }
            else
            {
                ViewBag.ShowFriendRequest = false;
            }

            return View(group);
        }

        public ActionResult Settings(int id)
        {
            var g = core.Groups.Find(id);
            if (g == null)
            {
                ViewBag.Detail = "Group Not found";
                return View("Error");
            }
            return View(g);
        }

        [HttpPost]
        public ActionResult Settings(Group g)
        {
            if (!PermissionHelper.IsOwner(g.GId))
                return RedirectToAction("Index");
            var group = core.Groups.Find(g.GId);
            if (ModelState.IsValid)
            {
                group.GName = g.GName;
                group.GPermission = g.GPermission;
                group.WallPermission = g.WallPermission;
                group.GDescription = g.GDescription;
                core.SaveChanges();
            }

            return View(g);
        }

        public ActionResult Requests(int id)
        {
            var requests = core.GroupRequests.Include(r => r.Profile).Where(r => r.GId == id);
            return View(requests);
        }

        public ActionResult UpdateAvatar(int id)
        {
            if (!PermissionHelper.IsOwner(id))
                return RedirectToAction("Index", "Home");

            var g = core.Groups.Find(id);
            return View(g);
        }
        [HttpPost]
        public string UpdateAvatar(HttpPostedFileBase file)
        {
            if (Request.Form["GId"] == null)
                return "No ok!";
            var gid = Convert.ToInt32(Request.Form["GId"]);
            if (!PermissionHelper.IsOwner(gid))
                return "You do not have permission to change this member avt";

            if (file.ContentType != "image/pjpeg" &&
                file.ContentType != "image/jpeg" &&
                file.ContentType != "image/png" &&
                file.ContentType != "image/gif")
                return "Image type not vailid";

            var realFileName = Path.GetFileName(file.FileName);

            var binary = new byte[file.ContentLength];
            file.InputStream.Read(binary, 0, file.ContentLength);

            var response = "";
            string path = ConfigurationManager.AppSettings["Avatars"];

            try
            {
                response = RemoteHelper.Put("https://apis.live.net/v5.0/" + path + "/files/GroupAvatar-" + Request.Form["GId"] + realFileName + "?access_token=" + core.AppToken.Find(1).access_token, binary);
            }
            catch
            {
                return "Error when upload image, try agian later!";
            }

            var parser = new JavaScriptSerializer();
            LiveFile liveResponse = parser.Deserialize<LiveFile>(response);

            Group group = core.Groups.Find(gid);
            group.Avatar = RemoteHelper.GetRedirect(liveResponse.source);
            core.SaveChanges();
            return "ok";
        }

        [HttpPost]
        public string UploadAttachment(HttpPostedFileBase file)
        {
            if (Request.Form["GId"] == null)
                return "{\"error\":\"It seem you are not loged in\"}";

            Guid userId = new Guid();
            if(!PermissionHelper.IsAuthenticated(ref userId))
                return "{\"error\":\"You do not logged in yet\"}";

            var gid = Convert.ToInt32(Request.Form["GId"]);
            if (!PermissionHelper.isMember(gid) && !PermissionHelper.IsOwner(gid))
                return "{\"error\":\"You do not have permission to upload\"}";

            bool isImage = false;
            if (file.ContentType == "image/pjpeg" ||
                file.ContentType == "image/jpeg" ||
                file.ContentType == "image/png" ||
                file.ContentType == "image/gif")
                isImage = true;

            var realFileName = Path.GetFileName(file.FileName);

            var binary = new byte[file.ContentLength];
            file.InputStream.Read(binary, 0, file.ContentLength);

            var response = "";

            string path = "";
            if (isImage)
                path = ConfigurationManager.AppSettings["Pictures"];
            else
                path = ConfigurationManager.AppSettings["Documents"];

            try
            {

                response = RemoteHelper.Put("https://apis.live.net/v5.0/" + path + "/files/Group" + Request.Form["GId"] + "-Wall-BY-" + userId.ToString() + "-AT-" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + "-NAME-" + realFileName + "?access_token=" + core.AppToken.Find(1).access_token, binary);
            }
            catch
            {
                return "{\"error\":\"Cannot upload your file, remember you can only upload Image and Documents (Portable Document Format (PDF) files, text files, and Microsoft Office files)" + path + ".\"}";
            }

            var parser = new JavaScriptSerializer();
            LiveFile liveResponse = parser.Deserialize<LiveFile>(response);

            Attachment att = new Attachment();
            att.isImage = isImage;
            att.UserId = userId;
            att.AName = realFileName;
            att.AKey = liveResponse.id;

            if (string.IsNullOrEmpty(Request.Form["isPublic"]))
                att.isPublic = false;
            else
                att.isPublic = true;

            if (isImage)
                att.ASource = RemoteHelper.GetRedirect(liveResponse.source);
            else
                att.ASource = liveResponse.source;

            core.Attachments.Add(att);
            core.SaveChanges();
            return "{\"AId\": " + att.AId + ", \"ASource\" : \"" + att.ASource + "\", \"isImage\": " + isImage.ToString().ToLower() + ", \"AName\" : \"" + realFileName + "\"}";
        }

        public ActionResult Members(int id)
        {
            var group = core.Groups.Find(id);
            var member = group.Members.OrderByDescending(m => m.UserId).Take(20);
            ViewBag.Group = group;
            if (!PermissionHelper.isMember(id) && !PermissionHelper.IsOwner(id))
            {
                ViewBag.ShowFriendRequest = true;
            }
            else
            {
                ViewBag.ShowFriendRequest = false;
            }
            return View(member);
        }
    }
}
